﻿using System;
using System.Collections.Generic;
using System.Linq;
using Pay.Core;
using Pay.Data;
using Pay.DTO;
using Pay.IService;
using Pay.Service.Cache;
using Pay.TO;

namespace Pay.Service.Service {
    public class CollectService : ServiceBase, ICollectService, IDisposable {
        private IUnitOfWork _iUnitOfWork;

        public CollectService(IUnitOfWork iUnitOfWork) : base(iUnitOfWork) {
            _iUnitOfWork = iUnitOfWork;
        }

        public collect_dto GetCollect(long UserId, long ProductId) {
            return context.Collects.Where(x => x.MerchantId == UserId && x.ProductId == ProductId).FromCacheFirstOrDefault<Collect, collect_dto>("Collects" + UserId);
        }
        /// <summary>
        /// 添加收藏
        /// </summary>
        /// <param name="UserId"></param>
        /// <param name="ProductId"></param>
        /// <returns></returns>
        public int Add(long UserId, long ProductId) {
            var model = new Collect();
            model.MerchantId = UserId;
            model.ProductId = ProductId;
            model.CraeteTime = DateTime.Now.ToUnix();
            context.Collects.Add(model);
            return _iUnitOfWork.Commit("Collects" + UserId);
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public int Remove(long Id) {
            var result = -1;
            var model = context.Collects.FirstOrDefault(x => x.Id == Id);
            if (model != null) {
                context.Collects.Remove(model);
                result = _iUnitOfWork.Commit("Collects" + model.MerchantId);
            }
            return result;
        }
        /// <summary>
        /// 删除收藏
        /// </summary>
        /// <returns>The collect.</returns>
        /// <param name="userId">User identifier.</param>
        /// <param name="productId">Product identifier.</param>
        public int DelCollect(long userId, long productId) {
            var collect = context.Collects.FirstOrDefault(x => x.MerchantId == userId && x.ProductId == productId);
            if (collect != null) {
                context.Collects.Remove(collect);
            }
            return _iUnitOfWork.Commit("Collects" + userId);
        }
        /// <summary>
        /// 我的收藏
        /// </summary>
        /// <param name="UserId"></param>
        /// <returns></returns>
        public List<collect_dto> GetCollects(long UserId) {
            return context.Collects.Where(x => x.MerchantId == UserId).FromCache<Collect, collect_dto>("Collects" + UserId);
        }
    }
}
